package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //添加购物项
    @PostMapping("add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        //判断shoppingCart是否存在
        ShoppingCart cart = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .one();
        //如果存在，number加1,然后修改
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartService.updateById(cart);
            return R.success(cart);
        }
        //不存在就保存,并且设置相关值
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setNumber(1);
        shoppingCartService.save(shoppingCart);
        return R.success(shoppingCart);
    }

    //查看购物车
    @GetMapping("list")
    public R list() {
        List<ShoppingCart> list = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .orderByDesc(ShoppingCart::getCreateTime)
                .list();
        return R.success(list);
    }

    //减少购物项
    @PostMapping("sub")
    public R sub(@RequestBody ShoppingCart sc) {
        ShoppingCart cart = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .eq(sc.getSetmealId() != null, ShoppingCart::getSetmealId, sc.getSetmealId())
                .eq(sc.getDishId() != null, ShoppingCart::getDishId, sc.getDishId())
                .one();
        if (cart.getNumber() > 1) {
            cart.setNumber(cart.getNumber() - 1);
            shoppingCartService.updateById(cart);
        }else {
            shoppingCartService.removeById(cart);
            cart.setNumber(0);
        }
        return R.success(cart);
    }

    //清除购物车
    @DeleteMapping("clean")
    public R clean() {
        shoppingCartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .remove();
        return R.success("清除成功");
    }
}
